/**
 * Copyright (c) 2009 Netflix-Flex_API Contributors.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of 
 * this software and associated documentation files (the "Software"), to deal in 
 * the Software without restriction, including without limitation the rights to 
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 
 * of the Software, and to permit persons to whom the Software is furnished to do 
 * so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all 
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE. 
 * */
package com.netflix.webapis.authenticate
{
	import com.netflix.webapis.ServiceBase;
	import com.netflix.webapis.ServiceFault;
	import com.netflix.webapis.ServiceStorage;
	import com.netflix.webapis.authenticate.events.AuthenticationFaultEvent;
	import com.netflix.webapis.authenticate.events.AuthenticationResultEvent;
	
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	
	import mx.rpc.AsyncToken;
	import mx.rpc.Responder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	import org.iotashan.oauth.OAuthRequest;

	/**
	* Result Event.
	*/	
	[Event(name="result",type="com.netflix.webapis.authenticate.events.AuthenticationResultEvent")]
	/**
	* Fault Event.
	*/	
	[Event(name="fault",type="com.netflix.webapis.authenticate.events.AuthenticationFaultEvent")]
	
	/**
	 * Services to Authorize your application with Netflix.
	 * @author jonbcampos
	 * 
	 */	
	public class AuthenticationService extends ServiceBase
	{
		
		public function AuthenticationService()
		{
			super();
		}
		
		/**
		 * Calls for the token to be able to call the access token service. 
		 * @param key Consumer key given by Netflix.
		 * @param secret Consumer secret given by Netflix.
		 * 
		 */		
		public function requestToken(key:String,secret:String):void
		{
			this.key = key;
			this.secret = secret;
			var service:HTTPService = new HTTPService();
			service.addEventListener(ResultEvent.RESULT,this.onServiceResult);
			service.addEventListener(FaultEvent.FAULT,this.onServiceFault);
			service.url = this.getRequestUrl();
			service.send();
		}
		
		/**
		 * @private
		 * Receives service result and dispatches result event. 
		 * @param event
		 * 
		 */		
		private function onServiceResult(event:ResultEvent):void
		{
			var s:Array = String(event.result).split("&");  
		    var array:Array;  
		    var o:Object = new Object();  
		    for each(var item:String in s)  
		    {  
		        array = item.split("=");  
		        o[array[0]] = array[1];  
		    }
		    
		    token = o.oauth_token as String;
		    tokenSecret = o.oauth_token_secret as String;
		    applicationName = o.application_name as String;
		    loginURL = unescape( o.login_url as String );
		    authorizationURL = unescape(loginURL) + "&application_name=" + applicationName + "&oauth_consumer_key=" + key;
		    
			var e:AuthenticationResultEvent = new AuthenticationResultEvent(token, tokenSecret, applicationName, loginURL, authorizationURL);
			dispatchEvent(e);
		}
		
		/**
		 * @private
		 * Dispatches fault event. 
		 * @param event
		 * 
		 */		
		private function onServiceFault(event:FaultEvent):void
		{
			dispatchEvent(new AuthenticationFaultEvent(AuthenticationFaultEvent.FAULT,new ServiceFault(event.fault.faultCode,event.fault.faultString,event.fault.faultDetail)));
		}
		
		/**
		 * @private 
		 * Creates the request url.
		 * @return request url
		 * 
		 */		
		private function getRequestUrl():String
		{
			var reqUrl:String = NETFLIX_BASE_URL + "oauth/request_token";
			var tokenRequest:OAuthRequest = new OAuthRequest("GET",reqUrl,null,consumer);
			return tokenRequest.buildRequest(SIG_METHOD);
		}
		
		/**
		 * Calls for an authorization url to authorize this application with a 
		 * user's account. Required to access user account information. There is 
		 * no result to listen to.
		 */		
		public static function getAuthorization():void
		{
			navigateToURL(new URLRequest(ServiceStorage.getInstance().authorizationURL));
		}

	}
}